package com.share.example.bcs.server.server.protocol.tcp;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 每新建一个tcp连接,才会实例化当前的TcpServerHandler对象
 */
@Slf4j
public class TcpServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {
        Channel channel = ctx.channel();

        //1.读取数据
        byte[] inputData = (byte[]) obj;
        String content = new String(inputData);
        String ip = channel.remoteAddress().toString();
        log.info("reciveMsg ip={},lenth={},content={}", ip, content.length(), content);

        //2.定义输出数
        String outData = "我是服务端,客户端你好,我收到了你请的请求!";

        //3.输出数据
        channel.writeAndFlush(outData.getBytes(CharsetUtil.UTF_8));
    }

    //服务异常了---调用exceptionCaught方法
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel channel = ctx.channel();
        log.info("异常:{},{}", channel.remoteAddress(), cause.getMessage());

        //定义输出数
        String outData = "发送的数据异常";

        //输出数据
        channel.writeAndFlush(outData.getBytes(CharsetUtil.UTF_8));

        //断开某个连接-----主动关闭
        channel.close();
    }

    //当客户端主动链接服务端的链接后，客户端会调用这个方法------------------------在服务这个函数无效
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.debug("客户端已连接:{}", ctx.channel().remoteAddress());
    }

    //客户端主动断开连接时---触发channelInactive方法执行
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.debug("连接断开:{}", ctx.channel().remoteAddress());
    }

}

